/**
 * Copyright 2019-2020 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "common/scope_allocator.h"
#include "common/aicore_util_attr_define.h"
#include "common/comm_log.h"
#include "graph/utils/attr_utils.h"

namespace fe {
ScopeAllocator::ScopeAllocator() { scope_id = 0; }

ScopeAllocator::~ScopeAllocator() {}

void ScopeAllocator::Init() { scope_id = 0; }

int64_t ScopeAllocator::AllocateScopeId(void) {
  scope_id++;
  return scope_id;
}

int64_t ScopeAllocator::GetCurrentScopeId() { return scope_id; }

bool ScopeAllocator::HasScopeAttr(ge::ConstOpDescPtr opdef) {
  if (opdef == nullptr) {
    return false;
  }

  if (opdef->HasAttr(SCOPE_ID_ATTR)) {
    return true;
  }
  return false;
}

bool ScopeAllocator::GetScopeAttr(ge::ConstOpDescPtr opdef, int64_t &scope_id) {
  if (opdef == nullptr) {
    return false;
  }

  if (ge::AttrUtils::GetInt(opdef, SCOPE_ID_ATTR, scope_id)) {
    return true;
  }
  return false;
}

bool ScopeAllocator::SetScopeAttr(ge::OpDescPtr opdef, int64_t scope_id) {
  if (opdef == nullptr) {
    REPORT_CM_ERROR("[SubGraphOpt][PostProcess][SetScopeAttr] opdef is nullptr.");
    return false;
  }

  if (!ge::AttrUtils::SetInt(opdef, SCOPE_ID_ATTR, scope_id)) {
    REPORT_CM_ERROR("[SubGraphOpt][PostProcess][SetScopeAttr] Set SCOPE_ID_ATTR failed.");
    return false;
  }
  return true;
}

bool ScopeAllocator::HasL1ScopeAttr(const ge::OpDescPtr &op_desc) {
  if (op_desc == nullptr) {
    return false;
  }
  return op_desc->HasAttr(L1_SCOPE_ID_ATTR);
}
bool ScopeAllocator::GetL1ScopeAttr(const ge::OpDescPtr &op_desc, int64_t &scope_id) {
  if (op_desc == nullptr) {
    return false;
  }

  return ge::AttrUtils::GetInt(op_desc, L1_SCOPE_ID_ATTR, scope_id);
}
bool ScopeAllocator::SetL1ScopeAttr(ge::OpDescPtr &op_desc, const int64_t &scope_id) {
  if (op_desc == nullptr) {
    CM_LOGE("op_desc is nullptr.");
    return false;
  }

  return ge::AttrUtils::SetInt(op_desc, L1_SCOPE_ID_ATTR, scope_id);
}

bool ScopeAllocator::ResetScopeId(int64_t scope_id) {
  if (scope_id < 0) {
    REPORT_CM_ERROR("[SubGraphOpt][PostProcess][ResetScopeId] Cannot reset scope_id, please check input value.");
    return false;
  }
  this->scope_id = scope_id;
  return true;
}
}  // namespace fe
